import 'dart:io';
import 'dart:typed_data';

import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'dart:async';

import 'package:flutter/services.dart';
import 'package:flutter_ble_ota/flutter_ble_ota.dart';
import 'package:flutter_ble_ota/ota_callbck.dart';
import 'package:flutter_ble_ota_example/permission_util.dart';
// import 'package:permission_handler/permission_handler.dart';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  final _flutterBleOtaPlugin = FlutterBleOta();

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: Column(
          children: [
            TextButton(
                onPressed: () {
                  // PermissionUtil.checkPermission(context, [Permission.bluetooth,Permission.location]);
                },
                child: Text("权限")),
            TextButton(
                onPressed: () async {
                  // Directory? d = await getExternalStorageDirectory();
                  // if(d!=null){
                  //   print(d.path);
                  //   Directory dd = Directory("${d.path}/myFile");
                  //   dd.create();
                  // }
                },
                child: Text("文件")),
            TextButton(
                onPressed: () async {
                  await _flutterBleOtaPlugin.dispose();
                },
                child: Text("dispose")),
            Center(
              child: TextButton(
                  onPressed: () async {
                    if (await _flutterBleOtaPlugin.initOTA()) {
                      var uuid = "22BC88C1-A0D7-AB1B-6976-54C62E094B4D";
                      if (Platform.isAndroid) {
                        uuid = "48:A0:10:36:6A:50";
                      }

                      if (await _flutterBleOtaPlugin.connect(uuid)) {
                        print("连接成功了**********************************");

                        var path =
                            "/storage/emulated/0/Android/data/com.alin.flutter_ble_ota_example/files/myFile/update.ufw";
                        if (Platform.isIOS) {
                          path = await readAndWriteFile();
                        }

                        _flutterBleOtaPlugin.startOTA(
                          path,
                          callback: BleOtaCallback(otaStart: () {
                            print("otaStart");
                          }, otaCanceled: () {
                            print("otaCanceled");
                          }, otaStop: () {
                            print("otaStop");
                          }, otaError: (code, msg) {
                            print("otaError  code=$code  msg=$msg");
                          }, otaProgress: (type, progress) {
                            print("otaProgress type=$type  progress=$progress");
                          }),
                        );
                      } else {
                        print("连接失败，请重试");
                      }
                    }
                  },
                  child: Text("OTA")),
            ),
          ],
        ),
      ),
    );
  }

  Future<String> readAndWriteFile() async {
    String fileName = "update.ufw";
    // var bytes = await rootBundle.load("asset/update.ufw");
    String dir = (await getApplicationDocumentsDirectory()).path;
    String filePath = "$dir/$fileName";
    // ByteBuffer buffer = bytes.buffer;
    // File file = await File(filePath).writeAsBytes(buffer.asUint8List(bytes.offsetInBytes, bytes.lengthInBytes));

    return filePath;
    //[log] readAndWriteImage /data/user/0/com.example.flutter_widgets/files/lovely_girl.jpg
    // /data/data/com.example.flutter_widgets/files/lovely_girl.jpg
  }

  @override
  void dispose() {
    _flutterBleOtaPlugin.dispose();
    // rootBundle.load(key)
    super.dispose();
  }
}
